import json
import os

from ninja import Router, Schema, Field, Query
from django.db import transaction

from apps.schemas import R
from apps.commom.advertisement import AdvertisementSerializer, IndexAdAndAdvertisementSchema
from models.models import Advertisement
from utils.auth import ManagerAuthBearer
from utils.constant import advertisement_types, introduce_types
from utils.decorators import handle_exception
from utils.file_handler import load_json_file

manager_index_router = Router(tags=["首页管理"], auth=ManagerAuthBearer())


@manager_index_router.get("/index/advertisements", summary="获取广告配置")
@handle_exception("获取首页广告失败")
def get_advertisement_config(request, data: Query[IndexAdAndAdvertisementSchema]):
    if data.type not in list(advertisement_types.keys()):
        return R.fail("广告类型错误")
    ads = Advertisement.objects.filter(type=advertisement_types.get(data.type, 1))
    return R.ok(AdvertisementSerializer(ads, many=True).data)


@manager_index_router.get("/index/introduces", summary="获取首页介绍配置")
@handle_exception("获取介绍类型失败")
def get_water_introduce(request, data: Query[IndexAdAndAdvertisementSchema]):
    if data.type not in list(introduce_types.keys()):
        return R.fail("介绍类型错误")
    data = load_json_file(f"conf/{introduce_types.get(data.type)}")
    return R.ok(data=data)


class IndexAdvertiseSchema(Schema):
    link: str = Field(default="", description="链接")
    type: str = Field(default="", description="类型")
    picture: str = Field(default="", description="图片")


@manager_index_router.post("/index/advertisement", summary="添加首页广告")
@handle_exception("添加首页广告失败")
def add_index_advertisement(request, ad: IndexAdvertiseSchema):
    Advertisement.objects.create(link=ad.link, type=advertisement_types.get(ad.type, 1),
                                 picture=ad.picture)
    return R.ok(msg="添加成功")


@manager_index_router.delete("/index/advertisement/{ad_id}", summary="删除首页广告")
@handle_exception("删除首页广告失败")
def delete_index_advertisement(request, ad_id: int):
    with transaction.atomic():
        ad = Advertisement.objects.get(id=ad_id)
        if not ad:
            return R.fail("广告不存在")
        os.remove(ad.picture)
        ad.delete()
    return R.ok(msg="删除成功")


@manager_index_router.put("/index/advertisement/{ad_id}", summary="修改首页广告")
@handle_exception("修改首页广告失败")
def update_index_advertisement(request, ad_id: int, ad_object: IndexAdvertiseSchema):
    with transaction.atomic():
        ad = Advertisement.objects.get(id=ad_id)
        if not ad:
            return R.fail("广告不存在")
        ad.link = ad_object.link
        ad.type = advertisement_types.get(ad_object.type, 1)
        os.remove(ad.picture)
        ad.picture = ad_object.picture
        ad.save()
    return R.ok(AdvertisementSerializer(ad).data)


class IndexIntroduceSchema(Schema):
    type: str = Field(description="类型[user_index|user_equity|agent_index|agent_package]",
                      pattern=r"[user_index|user_equity|agent_index|agent_package]")
    title: str = Field(description="标题")
    content: str = Field(description="内容")


@manager_index_router.post("/index/introduce", summary="修改首页介绍")
@handle_exception("修改首页介绍失败")
def add_index_introduce(request, ad: IndexIntroduceSchema):
    save_path = f"conf/{introduce_types.get(ad.type)}"
    with open(save_path, "w") as f:
        json.dump({"title": ad.title, "content": ad.content}, f, ensure_ascii=False)
    return R.ok(msg="修改成功")
